import store from './../store'
import config from '@/config/config'
import {isFlag} from "@/utils/util";

let websock = null;
let dateObject = null;//用来存储收到消息的对象

let accessKeySecret = "1rqnarzvbv6i19uxnxqaabj76edx2xvg"

let url = ''
let socketUrl = ''
const baseUrl = isFlag(process.env.NODE_ENV, 'development') ? config.baseUrl.dev : config.baseUrl.prod
if (baseUrl.indexOf('/llb') > -1) {
  url = "https://www.lianlaoban.cn/chatProd"
  socketUrl = "wss://www.lianlaoban.cn/chatWebsocket/websocket";
} else {
  url = "https://www.lianlaoban.cn/chatProd"
  socketUrl = "wss://www.lianlaoban.cn/chatWebsocket/websocket";
  // url = "http://192.168.10.176:17389"
  // socketUrl = "wss://192.168.10.176:17389/websocket";
}

export default {
  accessKeySecret: accessKeySecret
}

function initWebSocket() { //初始化weosocket,ws地址
                           // console.log("我要重连1111",wsuri)
                           // websock=null;
  websock = new WebSocket(socketUrl);
  websock.onmessage = function (e) {
    // console.log("我上线了")
    websocketonmessage(e);
  }
  websock.onclose = function (e) {
    // console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    websocketclose(e);
  }
  websock.onopen = function (e) {
    websocketOpen(e);
  }

  //连接发生错误的回调方法
  websock.onerror = function () {
    // console.log("WebSocket连接发生错误,状态码：" + websock.readyState);
  }
}

// 实际调用的方法
function sendSock(userId) {
  if (websock.readyState === websock.OPEN && userId != null) {
    //若是ws开启状态,则登录客服
  }
}

//数据接收
function websocketonmessage(e) {
  // console.log("来消息了")
  dateObject = JSON.parse(e.data);
  console.log("dateObject", dateObject)
}

//数据发送
function socketSend(agentData) {
  // console.log("数据发送", agentData)
  websock.send(agentData);
}

//关闭
function websocketclose(e) {
  // console.log("连接关闭 (" + e.code + "),状态码：" + websock.readyState);
  initWebSocket();
}

function websocketOpen(e) {
  // console.log("连接成功,状态码：" + websock.readyState);
  // console.log(store.state.user)
  setTimeout(() => {
    sendSock(store.state.user.userId);
  }, 500);

}

initWebSocket();

export {sendSock, socketSend}

